package com.gateway.plugin.tenant.handle;

import com.gateway.common.dto.PluginData;
import com.gateway.common.dto.RuleData;
import com.gateway.common.dto.convert.rule.impl.TenantRuleHandle;
import com.gateway.common.enums.PluginEnum;
import com.gateway.common.utils.JsonUtils;
import com.gateway.plugin.base.cache.CommonHandleCache;
import com.gateway.plugin.base.handler.PluginDataHandler;
import com.gateway.plugin.base.util.BeanHolder;
import com.gateway.plugin.base.util.CacheKeyUtils;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/14 10:20
 **/
public class TenantPluginDataHandler implements PluginDataHandler {
    public final static Supplier<CommonHandleCache<String, TenantRuleHandle>> CACHE_HANDLE = new BeanHolder<>(CommonHandleCache::new);

    @Override
    public void handlerRule(RuleData ruleData) {
        Optional.of(ruleData.getHandle())
                .ifPresent(ruleHandle -> {
                    TenantRuleHandle tenantRuleHandle = JsonUtils.stringToBean(ruleHandle, TenantRuleHandle.class);
                    CACHE_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), tenantRuleHandle);
                });
    }

    @Override
    public void handlerPlugin(PluginData pluginData) {
        PluginDataHandler.super.handlerPlugin(pluginData);
    }

    @Override
    public String pluginNamed() {
        return PluginEnum.TENANT.getName();
    }
}
